<template>
  <div class="param-main">
    <vxe-toolbar ref="xToolbar" :loading="loading">
      <template #buttons>
        <vxe-button status="primary" content="新增项目" @click="insertEvent"></vxe-button>
        <vxe-button status="primary" content="全部删除" @click="clearAllEvent"></vxe-button>
      </template>
    </vxe-toolbar>
    <vxe-table border show-overflow resizable keep-source ref="xTable" row-id="id" height="350px" :edit-rules="validRules"
      :edit-config="{
        trigger: 'click',
        mode: 'row',
        showUpdateStatus: false,
        showInsertStatus: false,
      }" :data="listData">
      <vxe-column type="seq" width="60"></vxe-column>
      <vxe-column field="itemType" title="商品类型" :edit-render="{}" :filter-multiple="false">
        <template #default="{ row }">
          <span>{{
            formatterFiled(row.itemType, "dictItemCode", "dictItemName", itemTypeList)
          }}</span>
        </template>
        <template #edit="{ row }">
          <vxe-select v-model="row.itemType" transfer placeholder="商品类型">
            <vxe-option v-for="item in itemTypeList" :key="item.dictItemCode" :value="item.dictItemCode"
              :label="item.dictItemName"></vxe-option>
          </vxe-select>
        </template>
      </vxe-column>
      <vxe-column title="操作" width="100">
        <template #default="{ row }">
          <vxe-button type="text" status="primary" @click="selectData(row, 'bottom')">选择项目</vxe-button>
        </template>
      </vxe-column>
      <vxe-column field="itemName" title="名称" :edit-render="{}">
        <template #edit="{ row }">
          <vxe-input v-model="row.itemName" type="text"></vxe-input>
        </template>
      </vxe-column>
      <!-- <vxe-column field="itemModel" title="规格型号" width="150" :edit-render="{}">
        <template #edit="{ row }">
          <vxe-input v-model="row.itemModel" type="text"></vxe-input>
        </template>
      </vxe-column> -->
      <vxe-column field="itemUnit" title="计量单位" width="110" :edit-render="{}">
        <template #edit="{ row }">
          <vxe-input v-model="row.itemUnit" type="text"></vxe-input>
        </template>
      </vxe-column>
      <vxe-column field="itemPrice" title="单价" width="100" :edit-render="{}">
        <template #edit="{ row }">
          <vxe-input v-model="row.itemPrice" type="float" @change="onNumberChange(row)" :digits="2"></vxe-input>
        </template>
      </vxe-column>
      <vxe-column field="itemNumber" title="数量" width="110" :edit-render="{}">
        <template #edit="{ row }">
          <vxe-input v-model="row.itemNumber" type="integer" @change="onNumberChange(row)" :digits="2"></vxe-input>
        </template>
      </vxe-column>
      <!-- <vxe-column field="laborCost" title="工时费" width="110" :edit-render="{}">
        <template #edit="{ row }">
          <vxe-input
            v-model="row.laborCost"
            type="integer"
            @change="onLaborCostChange(row)"
            :digits="2"
          ></vxe-input>
        </template>
      </vxe-column> -->
      <vxe-column field="itemTotalprice" title="总价" width="110">
        <!-- <template #edit="{ row }">
          <vxe-input v-model="row.itemTotalprice" type="float" :digits="2"></vxe-input>
        </template> -->
      </vxe-column>
      <vxe-column title="操作" width="100">
        <template #default="{ row }">
          <template>
            <vxe-button type="text" status="primary" @click="removeEvent(row)">删除</vxe-button>
          </template>
        </template>
      </vxe-column>
    </vxe-table>
    <div slot="footer" class="dialog-footer" style="margin-top: 20px">
      <el-button type="primary" @click="saveDetail()">保存</el-button>
    </div>
    <subject-list-dialog ref="modelForm" @ok="getCoaInit"></subject-list-dialog>
    <material-list-dialog ref="materialTable" @ok="getMaterialInit"></material-list-dialog>
    <user-list-dialog ref="userList" @ok="getUserInit"></user-list-dialog>
  </div>
</template>

<script>
import SubjectListDialog from "@/components/dialog/SubjectListDialog";
import MaterialListDialog from "@/components/dialog/MaterialListDialog";
import UserListDialog from "@/components/dialog/UserListDialog";
import { getDictionaryItemMap } from "@/api/common";
import { themeModelDetailBatch, themeModelDetailById } from "@/api/theme";
export default {
  name: "DetailTableDialog",
  components: { SubjectListDialog, MaterialListDialog, UserListDialog },
  data () {
    const numberValid = ({ cellValue }) => {
      if (cellValue && cellValue <= 0) {
        return new Error("格式不正确，必须大于0");
      }
    };
    return {
      loading: false,
      listData: [],
      itemTypeList: [],
      currentRow: {},
      validRules: {
        itemType: [{ required: true, message: "商品类型不能为空" }],
        itemName: [{ required: true, message: "名称不能为空" }],
        itemUnit: [{ required: true, message: "计量单位不能为空" }],
        itemPrice: [
          { required: true, message: "单价不能为空" },
          { validator: numberValid },
        ],
        itemNumber: [
          { required: true, message: "数量不能为空" },
          { validator: numberValid },
        ],
        // laborCost: [{ validator: numberValid }],
        // itemTotalprice: [
        //   { required: true, message: "总价不能为空" },
        //   { validator: numberValid },
        // ],
      },
    };
  },
  props: {
    templateId: String,
    carId: String
  },
  created () { },
  mounted () {
    this.getDictInit();
    this.getDetaiList();
  },
  methods: {
    /**
     * 获取字典初始化数据
     */
    getDictInit () {
      let param = { codeArr: "itemType" };
      getDictionaryItemMap(param).then((res) => {
        let data = res.data;
        if (data && data.code == 0) {
          this.itemTypeList = data.data.itemType;
        }
      });
    },
    getMaterialInit (val) {
      const $table = this.$refs.xTable;
      this.currentRow.itemId = val.id;
      this.currentRow.itemName = val.name;
      this.currentRow.itemUnit = val.unit;
      this.currentRow.supplierId = val.supplierId;
      this.currentRow.supplierName = val.supplier;
      this.currentRow.itemPrice = val.wholesaleDecimal;
      this.currentRow.itemNumber = 1;
      this.currentRow.itemTotalprice = val.wholesaleDecimal;
      this.currentRow.laborCost = 0;
      $table.reloadRow(this.currentRow);
      this.countTotalPrice();
    },
    getCoaInit (val) {
      const $table = this.$refs.xTable;
      this.currentRow.itemId = val.itemId;
      this.currentRow.itemName = val.itemName;
      this.currentRow.itemNumber = val.itemNumber;
      this.currentRow.itemPrice = val.itemPrice;
      this.currentRow.itemTotalprice = val.itemTotalprice;
      this.currentRow.itemUnit = val.itemUnit;
      this.currentRow.itemModel = val.itemModel;
      this.currentRow.laborCost = 0;
      $table.reloadRow(this.currentRow);
      this.countTotalPrice();
    },
    getUserInit (val) {
      const $table = this.$refs.xTable;
      this.currentRow.itemId = val.id;
      this.currentRow.itemName = val.username;
      this.currentRow.itemNumber = 1;
      this.currentRow.itemPrice = val.skillPrice;
      this.currentRow.itemTotalprice = val.skillPrice;
      this.currentRow.itemUnit = val.skillPriceType == '0' ? "时薪" : "件薪";
      // this.currentRow.itemModel = val.itemModel;
      // this.currentRow.laborCost = 0;
      $table.reloadRow(this.currentRow);
      this.countTotalPrice();
    },
    onNumberChange (row) {
      const $table = this.$refs.xTable;
      row.itemTotalprice = Number(row.itemPrice) * Number(row.itemNumber);
      $table.reloadRow(row);
      this.countTotalPrice();
    },
    onLaborCostChange (row) {
      const $table = this.$refs.xTable;
      row.itemTotalprice = Number(row.itemPrice) * Number(row.itemNumber);
      $table.reloadRow(row);
      this.countTotalPrice();
    },
    countTotalPrice () {
      const tableData = this.$refs.xTable.getTableData().tableData;
      let totalPrice = 0;
      tableData.forEach((element) => {
        totalPrice = totalPrice + Number(element.itemTotalprice);
      });
      // this.$set(this.createForm, "totalPrice", totalPrice);
    },
    getDetaiList () {
      let param = {
        id: this.templateId,
      };
      themeModelDetailById(param).then((res) => {
        let data = res.data;
        if (data && data.code == 0) {
          if (data.data.detailList) {
            this.listData = data.data.detailList;
          }
        }
      });
    },
    /**
     * 获取码值
     */
    formatterFiled (cellValue, key, val, list) {
      let item = list.find((item) => item[key] === cellValue);
      return item ? item[val] : "";
    },
    selectData (val) {
      if (!val.itemType) {
        this.$message({
          message: "请先选择商品类型",
          //type 取值 success(成功) /warning(警告)/info(消息)/error(错误)/;
          type: "warning",
        });
        return;
      }
      this.currentRow = val;
      if (val.itemType == "01") {
        this.$refs.materialTable.add(this.carId, "0");
      } else if (val.itemType == "02") {
        this.$refs.materialTable.add(this.carId, "1");
      } else if (val.itemType == "04" || val.itemType == "05") {
        this.$refs.modelForm.add(this.carId);
      } else if (val.itemType == "03") {
        this.$refs.userList.add();
      }
    },

    /**
     * 保存
     * */
    async saveDetail () {
      const $table = this.$refs.xTable;
      const errMap = await $table.validate().catch((errMap) => errMap);
      if (errMap) {
        // this.$message.success("保存成功");
        return;
      }
      const tableData = this.$refs.xTable.getTableData().tableData;
      let recordList = [];
      tableData.forEach((element) => {
        let el;
        if (element.id && element.id.includes("row")) {
          el = Object.assign(element, { id: null });
        } else {
          el = element;
        }
        recordList.push(el);
      });
      let param = {
        templateId: this.templateId,
        recordList: recordList,
      };
      themeModelDetailBatch(param).then((res) => {
        const data = res.data;
        if (data.code == 0) {
          this.$message.success("保存成功");
          this.$emit("ok");
        } else {
          this.$message.error(data.data || "保存失败");
        }
      });
    },
    /**
     * 插入数据
     */
    async insertEvent () {
      const $table = this.$refs.xTable;
      const newRecord = {};
      const { row: newRow } = await $table.insert(newRecord);
      await $table.setActiveRow(newRow);
    },
    async clearEvent () {
      const $table = this.$refs.xTable;
      $table.remove();
    },
    async clearAllEvent () {
      this.$confirm("确定删除所有数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const $table = this.$refs.xTable;
          if ($table) {
            $table.remove();
          }
        })
        .catch(() => { });
    },
    /**
     * 删除数据
     * @param row
     * @returns {Promise<void>}
     */
    async removeEvent (row) {
      this.$confirm("确定删除该数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const $table = this.$refs.xTable;
          if ($table) {
            $table.remove(row);
          }
        })
        .catch(() => { });
    },
  },
};
</script>

<style scoped></style>
